package servlets;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import app.AudioPlayer;
import app.RemoteStructure;

@WebServlet("/RemotePlayer")
public class RemotePlayer extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private AudioPlayer audioPlayer;
	private RemoteStructure remoteStructure;

	public RemotePlayer() {
		super();
		audioPlayer = AudioPlayer.getInstance();
		remoteStructure = RemoteStructure.getInstance();
	}

	private Document getXMLContent(HttpServletRequest request)
			throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = request.getReader();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line);
		}

		Document doc = DocumentHelper.createDocument();
		try {
			doc = DocumentHelper.parseText(sb.toString());
		} catch (DocumentException e) {
			doc = null;
			System.err.println("Chyba parsovani vstupniho XML");
		}

		return doc;
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Document doc = DocumentHelper.createDocument();
		Element status = DocumentHelper.createElement("status");
		status.addAttribute("status", "" + audioPlayer.getStatus());
		status.addAttribute("song", audioPlayer.getTrackName());
		status.addAttribute("path", remoteStructure.remoteDirectory);
		status.addAttribute("volume", ""+audioPlayer.getVolume());
		status.addAttribute("progress", ""+audioPlayer.getProgress());

		Element playlist = DocumentHelper.createElement("playlist");
		for (File file : audioPlayer.getPlaylist()) {
			Element item = DocumentHelper.createElement("item");
			item.addAttribute("name", file.getName());
			playlist.add(item);
		}

		status.add(playlist);
		doc.add(status);
		doc.setRootElement(status);

		response.setCharacterEncoding("utf-8");
	    response.setContentType("application/xml;");
		response.getWriter().write(doc.asXML());
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// nacist parametry
		String add = request.getParameter("add");
		String control = request.getParameter("control");
		String volume = request.getParameter("volume");

		if (add != null && add.length() > 0) {
			Document doc = getXMLContent(request);
			if (doc != null) {
				System.out.println(doc.asXML());

				@SuppressWarnings("unchecked")
				List<Node> trackList = doc.selectNodes("tracklist/track");

				boolean check = true;
				for (Node node : trackList) {
					try {
						int id = Integer.valueOf(node.valueOf("@id"));
						File file = remoteStructure.fileList.get(id);
						if (file.exists()) {
							audioPlayer.addtrack(file);
						} else {
							check = false;
						}
					} catch (NumberFormatException e) {
						check = false;
					}
				}

				if (check) {
					response.setStatus(HttpServletResponse.SC_CREATED);
				} else {
					response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
				}
			}

			return;
		}

		if (control != null && control.length() > 0) {
			switch (control) {
			case "play": {
				audioPlayer.play();
				break;
			}
			case "next": {
				audioPlayer.playNext();
				break;
			}
			case "stop": {
				audioPlayer.stopPlaying();
				break;
			}
			default:
				
			}
			return;
		}
		
		if (volume != null && volume.length() > 0) {
			audioPlayer.setVolume(Integer.valueOf(volume));
			return;
		}

		response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
	}

}
